package com.base.cn.platform.os.controller.web.qa.question;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.rsa.WebRsaUtils;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.qa.qatag.QaTagService;
import com.base.cn.platform.os.service.course.qa.qatype.QaTypeService;
import com.base.cn.platform.os.service.course.qa.question.QaQuestionService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 前台问答Controller(登录拦截)
 *
 * @author LIZHIPENG
 * @create 2018-05-31 下午 3:29
 */
@Controller
@RequestMapping("/web/uc/qa")
public class WebUcQuestionController extends WebBaseController {

    @Autowired
    private QaQuestionService questionService;
    @Autowired
    private QaTagService qaTagService;
    @Autowired
    private QaTypeService qaTypeService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseCatalogService catalogService;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private SysTeacherService teacherService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**滑图验证码偏差值*/
    private Integer vOffset = 5;

    /**
     * 校验用户是否可以免费提问
     * @param request
     * @return
     */
    @RequestMapping("/checkUserIsQuestion")
    @ResponseBody
    public Map<String, Object> checkUserIsQuestion(HttpServletRequest request){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> result = questionService.checkUserIsQuestion(userId);
        return result;
    }

    /**
     * 初始化提问页面
     * @param model
     * @param request
     * @param packageId 针对套餐提问的套餐ID
     * @param courseId 针对课程提问的课程ID
     * @param catalogId 针对章节提问的章节ID
     * @param teacherId 针对讲师提问的讲师ID
     * @param type 提问类型：1.免费提问，2.付费提问
     * @return
     */
    @RequestMapping("/initSaveQuestionView")
    public String initSaveQuestionView(Model model, HttpServletRequest request,
                                       @RequestParam(value = "packageId",required = false) BigDecimal packageId,
                                       @RequestParam(value = "courseId",required = false) BigDecimal courseId,
                                       @RequestParam(value = "catalogId",required = false) BigDecimal catalogId,
                                       @RequestParam(value = "teacherId",required = false) BigDecimal teacherId,
                                       @RequestParam("type")Integer type,
                                       @RequestParam(value = "isCourse",required = false ,defaultValue = "false") boolean isCourse) throws Exception{
        model.addAttribute("packageId",packageId);
        model.addAttribute("courseId",courseId);
        model.addAttribute("catalogId",catalogId);
        model.addAttribute("teacherId",teacherId);
        model.addAttribute("isCourse",isCourse);
        model.addAttribute("type",type);

        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);

        //如果是针对讲师提问，则查出讲师负责的问答分类，否则查询所有分类
        List<Map<String, Object>> qaTypeList = new ArrayList<>();
        if(DataUtil.idIsNotNull(teacherId)){
            Map<String, Object> teacher = teacherService.findSysTeacherById(teacherId, false, false, false, false, true);
            if(ObjectUtils.isNotEmpty(teacher)){
                qaTypeList.add((Map<String, Object>)teacher.get("qaType"));
                model.addAttribute("questionFee", teacher.get("questionFee"));
                model.addAttribute("teacherName", teacher.get("teacherName"));
            }
        }else {
            qaTypeList = qaTypeService.queryQaTypeList(params);
        }
        model.addAttribute("qaTypeList", qaTypeList);

        //查询问答标签
        List<Map<String, Object>> tagList = qaTagService.queryQaTagList(params);
        model.addAttribute("tagList", tagList);

        if(type == 1){
            if(DataUtil.idIsNotNull(packageId) || DataUtil.idIsNotNull(courseId) || DataUtil.idIsNotNull(catalogId)){
                if(DataUtil.idIsNotNull(packageId)){
                    Map<String, Object> packageCourse = courseService.findCourseById(packageId, false, false, false, false);
                    model.addAttribute("packageCourse", packageCourse);
                }
                if(DataUtil.idIsNotNull(courseId)){
                    Map<String, Object> course = courseService.findCourseById(courseId, false, false, false, false);
                    model.addAttribute("course", course);
                }
                if(DataUtil.idIsNotNull(catalogId)){
                    Map<String, Object> courseCatalog = catalogService.findCourseCatalogById(catalogId, false, false, false, false);
                    model.addAttribute("courseCatalog", courseCatalog);
                }
            }else {
                List<Map<String, Object>> packageList = new ArrayList<>();//套餐列表
                List<Map<String, Object>> courseList = new ArrayList<>();//课程列表

                BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
                params.remove("status");
                params.put("userId", userId);
                params.put("validTime",new Date());
                List<Map<String, Object>> courseBuyRecordList = courseBuyRecordService.findCourseBuyRecordList(params, true);

                if(ObjectUtils.isNotEmpty(courseBuyRecordList)){
                    for (Map<String, Object> courseBuyRecord : courseBuyRecordList) {
                        if(CourseType.COURSE_TYPE_PACKAGE.getKey().equals(courseBuyRecord.get("courseTypeKey"))){
                            packageList.add((Map<String, Object>)courseBuyRecord.get("course"));
                        }else {
                            courseList.add((Map<String, Object>)courseBuyRecord.get("course"));
                        }
                    }
                }

                model.addAttribute("packageList", packageList);
                model.addAttribute("courseList", courseList);
            }
        }
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        return resultPage("/qa/question/save-qa-question");
    }

    /**
     * 提问方法
     * @param request
     * @param question 问题数据
     * @return
     */
    @RequestMapping("/saveQuestion")
    @ResponseBody
    public Map<String, Object> saveQuestion(HttpServletRequest request,
                                            @RequestBody Map<String, Object> question,
                                            @RequestParam("sign") String sign) throws Exception{
        String _gapLeft = (String)question.get("gapLeft");
        String _moveLeft = (String) question.get("moveLeft");
        _gapLeft = WebRsaUtils.decrypt(customCacheChannel,sign,_gapLeft,false);
        _moveLeft = WebRsaUtils.decrypt(customCacheChannel,sign,_moveLeft,true);
        Integer gapLeft = Integer.valueOf(_gapLeft);
        Integer moveLeft = Integer.valueOf(_moveLeft);
        Map<String,Object> resultMap = null;
        if(gapLeft ==0 || moveLeft==0 || Math.abs(gapLeft-moveLeft)>vOffset){
            resultMap = ResultUtil.ERROR("验证码验证失败，请重新验证");
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
            return resultMap;
        }
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        question.put("userId", userId);
        resultMap = questionService.saveQuestion(question);
        if(!ResultUtil.getSuccess(resultMap)){
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return resultMap;
    }
}
